using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Text.Json;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// SSL连接测试服务 - 专门用于诊断和修复SSL连接问题
    /// </summary>
    public class SSLConnectionTestService
    {
        private readonly ILogger<SSLConnectionTestService> _logger;

        public SSLConnectionTestService(ILogger<SSLConnectionTestService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 测试智谱AI的SSL连接
        /// </summary>
        public async Task<SSLTestResult> TestZhipuAIConnectionAsync(string apiKey, string baseUrl = "https://open.bigmodel.cn/api/paas/v4")
        {
            var result = new SSLTestResult
            {
                ServiceName = "智谱AI",
                BaseUrl = baseUrl,
                TestTime = DateTime.Now
            };

            try
            {
                _logger.LogInformation($"开始测试智谱AI SSL连接: {baseUrl}");

                // 创建多种不同的SSL配置进行测试
                var testConfigs = CreateTestConfigurations();
                foreach (var config in testConfigs)
                {
                    try
                    {
                        var testResult = await TestSingleConfiguration(config.client, config.configName, apiKey, baseUrl);
                        result.ConfigurationResults.Add(testResult);

                        if (testResult.Success)
                        {
                            result.Success = true;
                            result.RecommendedConfiguration = config.configName;
                            _logger.LogInformation($"智谱AI SSL连接成功，推荐配置: {config.configName}");
                            break;
                        }
                    }
                    finally
                    {
                        config.client.Dispose();
                    }
                }

                if (!result.Success)
                {
                    result.ErrorMessage = "所有SSL配置都无法连接到智谱AI服务";
                    _logger.LogError("智谱AI SSL连接失败，所有配置都无法连接");
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = ex.Message;
                _logger.LogError(ex, "智谱AI SSL连接测试异常");
            }

            return result;
        }

        /// <summary>
        /// 创建标准HttpClient
        /// </summary>
        private HttpClient CreateStandardHttpClient()
        {
            return new HttpClient();
        }

        /// <summary>
        /// 创建宽松SSL验证的HttpClient
        /// </summary>
        private HttpClient CreateRelaxedSSLHttpClient()
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                _logger.LogDebug($"SSL证书验证: {sslPolicyErrors}");
                return true; // 允许所有证书
            };
            return new HttpClient(handler);
        }

        /// <summary>
        /// 创建仅支持TLS 1.2的HttpClient
        /// </summary>
        private HttpClient CreateTls12OnlyHttpClient()
        {
            var handler = new HttpClientHandler();
            handler.SslProtocols = SslProtocols.Tls12;
            handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            return new HttpClient(handler);
        }

        /// <summary>
        /// 创建仅支持TLS 1.3的HttpClient
        /// </summary>
        private HttpClient CreateTls13OnlyHttpClient()
        {
            var handler = new HttpClientHandler();
            handler.SslProtocols = SslProtocols.Tls13;
            handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            return new HttpClient(handler);
        }

        /// <summary>
        /// 测试单个配置
        /// </summary>
        private async Task<ConfigurationTestResult> TestSingleConfiguration(HttpClient client, string configName, string apiKey, string baseUrl)
        {
            var result = new ConfigurationTestResult
            {
                ConfigurationName = configName,
                TestTime = DateTime.Now
            };

            try
            {
                // 配置请求头
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                client.DefaultRequestHeaders.Add("User-Agent", "DocumentCreationSystem/1.0");
                client.Timeout = TimeSpan.FromSeconds(30);

                // 创建测试请求
                var request = new
                {
                    model = "GLM-4-Flash-250414",
                    messages = new[]
                    {
                        new { role = "user", content = "测试连接" }
                    },
                    max_tokens = 10,
                    temperature = 0.1
                };

                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 发送请求
                var response = await client.PostAsync($"{baseUrl}/chat/completions", content);

                result.Success = response.IsSuccessStatusCode;
                result.StatusCode = (int)response.StatusCode;
                result.ResponseTime = DateTime.Now - result.TestTime;

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    result.ResponsePreview = responseContent.Length > 200 ? 
                        responseContent.Substring(0, 200) + "..." : responseContent;
                    _logger.LogDebug($"配置 {configName} 测试成功");
                }
                else
                {
                    result.ErrorMessage = $"HTTP {response.StatusCode}: {await response.Content.ReadAsStringAsync()}";
                    _logger.LogDebug($"配置 {configName} 测试失败: {result.ErrorMessage}");
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = ex.Message;
                result.ResponseTime = DateTime.Now - result.TestTime;
                _logger.LogDebug($"配置 {configName} 测试异常: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 获取推荐的HttpClient配置
        /// </summary>
        public HttpClient CreateRecommendedHttpClient(string recommendedConfiguration)
        {
            return recommendedConfiguration switch
            {
                "标准配置" => CreateStandardHttpClient(),
                "宽松SSL验证" => CreateRelaxedSSLHttpClient(),
                "TLS 1.2 专用" => CreateTls12OnlyHttpClient(),
                "TLS 1.3 专用" => CreateTls13OnlyHttpClient(),
                _ => CreateRelaxedSSLHttpClient() // 默认使用宽松配置
            };
        }

        /// <summary>
        /// 返回配置名称和HttpClient的元组
        /// </summary>
        private (HttpClient client, string configName)[] CreateTestConfigurations()
        {
            return new[]
            {
                (CreateStandardHttpClient(), "标准配置"),
                (CreateRelaxedSSLHttpClient(), "宽松SSL验证"),
                (CreateTls12OnlyHttpClient(), "TLS 1.2 专用"),
                (CreateTls13OnlyHttpClient(), "TLS 1.3 专用")
            };
        }
    }

    /// <summary>
    /// SSL测试结果
    /// </summary>
    public class SSLTestResult
    {
        public string ServiceName { get; set; } = string.Empty;
        public string BaseUrl { get; set; } = string.Empty;
        public bool Success { get; set; }
        public string? ErrorMessage { get; set; }
        public string? RecommendedConfiguration { get; set; }
        public DateTime TestTime { get; set; }
        public List<ConfigurationTestResult> ConfigurationResults { get; set; } = new();
    }

    /// <summary>
    /// 配置测试结果
    /// </summary>
    public class ConfigurationTestResult
    {
        public string ConfigurationName { get; set; } = string.Empty;
        public bool Success { get; set; }
        public int StatusCode { get; set; }
        public string? ErrorMessage { get; set; }
        public string? ResponsePreview { get; set; }
        public TimeSpan ResponseTime { get; set; }
        public DateTime TestTime { get; set; }
    }
}
